package com.iris.netty.netty5;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class Server {
    public static void main(String[] args) {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.group(boss,worker);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast(new StringEncoder());
                socketChannel.pipeline().addLast(new ServerHandler());
            }
        });
        //serverSocketchannel的设置，链接缓冲池的大小
        serverBootstrap.option(ChannelOption.SO_BACKLOG, 2048);
        //socketchannel的设置,维持链接的活跃，清除死链接
        serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
        //socketchannel的设置,关闭延迟发送
        serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);
        //绑定端口
        ChannelFuture future = serverBootstrap.bind(8888);
        System.out.println("start");
        //等待服务端关闭
        try {
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //释放资源
            boss.shutdownGracefully();
            worker.shutdownGracefully();

        }


    }
}
